package com.ailanyin.security.utils;

import com.ailanyin.common.model.SysUser;
import com.ailanyin.security.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2022/2/17 0017 下午 13:59
 */
public class SecurityUtil {

    public static SysUser getCurrentUser() {
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            LoginUser adminUserDetails = (LoginUser) auth.getPrincipal();
            return adminUserDetails.getUser();
        } catch (Exception e) {
            return null;
        }
    }

    public static SysUser getLoginUser() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        LoginUser adminUserDetails = (LoginUser) auth.getPrincipal();
        return adminUserDetails.getUser();
    }


    public static String getLoginUsername() {
        return getLoginUser().getUserName();
    }

}
